package com.hxzy.controller.login;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.resp.R;
import com.hxzy.controller.login.req.LoginReq;
import com.hxzy.controller.login.resp.LoginResp;
import com.hxzy.entity.UserinfoWy;
import com.hxzy.service.UserinfoWyService;
import com.hxzy.util.DemoThreadLocalUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Desc 描述
 * @Author: admin
 * @Date: 2023/08/16/10:24
 */
@Api(tags = "后台-登录")
@RequestMapping(value = "/api")
@RestController
public class LoginController {

    @Autowired
    private UserinfoWyService userinfoWyService;


    @ApiOperation(value = "登录")
    @PostMapping(value = "/login")
    public R<String>  login(@RequestBody @Validated LoginReq req){
        //如果手机号不为空，必须要验证格式有效性
        if(StrUtil.isNotBlank(req.getMobile())){
            String regex="^(1[3,4,5,6,8,9]\\d{9})$";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(req.getMobile());
            if(!matcher.matches()){
                return R.build(AckCode.PHONE_NUMBER_ERROR);
            }
        }  
        //登录，并且生成令牌
        UserinfoWy userinfoWy=this.userinfoWyService.login(req);

        //需要对令牌加密
        String token=userinfoWy.getToken();

        //对令牌加密 内容 https://doc.hutool.cn/pages/JWTUtil/#%E4%BB%8B%E7%BB%8D
        Map<String, Object> map = new HashMap<String, Object>() {
            private static final long serialVersionUID = 1L;
            {
                put("token",  token);
            }
        };

        String jwtToken = JWTUtil.createToken(map, "jfsalkdjfwruw2r3095u3gdlkfmaguirnadgiae0iw0wtuq3093482".getBytes());

        return R.okHasData(jwtToken);
    }


    /**
     * 获取用户信息
     * @return
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping(value = "/user/info")
    public R<LoginResp> userInfo(){
        LoginResp loginResp = DemoThreadLocalUtil.loginRespThreadLocal.get();
        return R.okHasData(loginResp);
    }

    /**
     * 退出
     * @return
     */
    @ApiOperation(value = "退出")
    @PostMapping(value = "/logout")
    public R logout(){
        LoginResp loginResp = DemoThreadLocalUtil.loginRespThreadLocal.get();
        String token=loginResp.getToken();
        this.userinfoWyService.logout(token);
        return R.ok();
    }

}
